package com.paic.icore.test.demo.config;

import com.paic.icore.test.demo.util.MapperRefresh;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * describe:
 *
 * @author huxingjie
 * @date 2019/05/16
 * @since 3.6
 */
@Configuration
public class DataSourceConfig {
    @Autowired
    private Environment env;


    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        // 获取properties中的对应配置信息
        String mapperPackage = env.getProperty("spring.mybatis.mapperLocations");
        String dialect = "mysql";
        Properties properties = new Properties();
        properties.setProperty("dialect", dialect);
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setConfigurationProperties(properties);
        Resource[] resources = null;
        // 设置MapperLocations路径
        if (!StringUtils.isEmpty(mapperPackage)) {
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            resources = resourcePatternResolver.getResources(mapperPackage);
            sessionFactory.setMapperLocations(resources);
        }
        SqlSessionFactory sqlSessionFactory = sessionFactory.getObject();
        new Thread(new MapperRefresh(resources, sqlSessionFactory.getConfiguration())).start();
        return sqlSessionFactory;
    }
}

    